package cn.liufuwen.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.liufuwen.entity.UserDTO;
import lombok.extern.slf4j.Slf4j;

/**
 * SpringBoot中使用Interceptorr拦截器类
 * 判断是否登录的使用
 */
@Slf4j
public class MyInterceptor implements  HandlerInterceptor {
	@Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) 
    		throws Exception {
		log.info("拦截器："+httpServletRequest.toString());
        //只有返回true才会继续向下执行，返回false取消当前请求
        boolean flag = true;
        UserDTO userDTO = (UserDTO)httpServletRequest.getSession().getAttribute("USER_SESSION_KEY");
        
        if(userDTO == null){
        	
        	httpServletResponse.sendRedirect("/hello/login");
        	flag = false;
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        System.out.println("myinterc posthandler");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

        System.out.println("myinterc aftercompletion");
    }

}
